﻿using System;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Linq;
using System.DirectoryServices;
using System.Collections.Generic;

namespace FormApplicationInteractionAd
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        
        
        private void loadAdInfoButton_Click(object sender, EventArgs e)
        {
            if ((this.textUserId.Text == null) || ("".Equals(this.textUserId.Text.Trim())))
            {
                //messaggio di alert
                if ((this.textBoxSurname.Text == null) || ("".Equals(this.textBoxSurname.Text.Trim())))
                {
                    System.Windows.Forms.MessageBox.Show("Attenzione o il campo User ID o il campo Cognome devone essere valorizzati con un valore.", "ERROR", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
                else 
                {
                    //elaborazione con il cognome.
                    //this.clearAllTextArea();
                    this.getUserIdInfo(this.textBoxSurname.Text.Trim());
                }
            }else
            {
                //elaborazione
                //this.clearAllTextArea();
                //this.textBoxSurname.Clear();
                this.getAdGroupInfo(this.textUserId.Text.Trim());
            }

        }

        private void getUserIdInfo(String surname)
        {
            try
            {
                this.tabControlPanel.Cursor = Cursors.WaitCursor;
                //NEW-VERSION: RECUPERO IL REALM UTILIZZANDO AD
                String ADEntry = System.Environment.GetEnvironmentVariable("USERDNSDOMAIN");
                //Console.WriteLine("AD Entry found: " + ADEntry);
                using (DirectoryEntry de = new DirectoryEntry("LDAP://" + ADEntry))
                {
                    using (DirectorySearcher adSearch = new DirectorySearcher(de))
                    {
                        adSearch.Filter = string.Format("(sn={0})", surname.ToUpper());
                        adSearch.PropertiesToLoad.Add("samaccountname");
                        adSearch.PropertiesToLoad.Add("displayname");

                        SearchResultCollection adSearchResultCollection= adSearch.FindAll();
                                             
                        if (adSearchResultCollection.Count == 0)
                        {
                             this.txtErrorMsg.BackColor = System.Drawing.Color.Red;
                             this.txtErrorMsg.Text = "No User Found!";
                        }
                        else if (adSearchResultCollection.Count == 1)
                        {
                            ResultPropertyCollection myResultPropColl;
                            myResultPropColl = adSearchResultCollection[0].Properties;
                            String uid = myResultPropColl["samaccountname"].ToString();                            
                            this.getAdGroupInfo(uid); 
                        }
                        else 
                        {
                            // + di un utente                                                        
                            foreach(SearchResult sr in adSearchResultCollection)
                            {
                                ResultPropertyCollection myResultPropColl;
                                myResultPropColl = sr.Properties;
                                foreach (String ldapField in myResultPropColl.PropertyNames)
                                {
                                    foreach (Object myCollection in myResultPropColl[ldapField])
                                    {
                                        this.richTextAreaInfoGrpAd.AppendText("["+ldapField+"]:"+myCollection + Environment.NewLine);
                                    }                                    
                                }
                                this.richTextAreaInfoGrpAd.AppendText("==============================================================================" + Environment.NewLine);
                                
                            }
                           
                        }                     
                                               
                    }
                }

                this.tabControlPanel.Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Attenzione! Errore nell'interrogazione di AD." + ex.Message, "ERROR", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                this.txtErrorMsg.BackColor = System.Drawing.Color.Red;
                this.txtErrorMsg.Text = "No User Found!";
            }
        }

        private void getAdGroupInfo(String userId)
        {
            try
            {
                this.tabControlPanel.Cursor = Cursors.WaitCursor;                
                String ADEntry = System.Environment.GetEnvironmentVariable("USERDNSDOMAIN");
                //Console.WriteLine("AD Entry found: " + ADEntry);
                using (DirectoryEntry de = new DirectoryEntry("LDAP://" + ADEntry))
                {
                    using (DirectorySearcher adSearch = new DirectorySearcher(de))
                    {
                        adSearch.Filter = string.Format("(sAMAccountName={0})",userId);

                        SearchResult adSearchResult = adSearch.FindOne();
                        if (adSearchResult != null)
                        {
                            // Get the properties of the 'mySearchResult'.
                            ResultPropertyCollection myResultPropColl;
                            myResultPropColl = adSearchResult.Properties;
                            foreach (String ldapField in myResultPropColl.PropertyNames)
                            {
                                foreach (Object myCollection in myResultPropColl[ldapField])
                                {
                              
                                    if ("displayname".Equals(ldapField))
                                        this.textName.Text = myCollection.ToString();
                                    if ("samaccountname".Equals(ldapField))
                                        this.textLoginId.Text = myCollection.ToString();
                                    if ("logoncount".Equals(ldapField))
                                        this.textLogonCount.Text = myCollection.ToString();
                                    if ("company".Equals(ldapField))
                                        this.textCompany.Text = myCollection.ToString();
                                    if ("telephonenumber".Equals(ldapField))
                                        this.textPhoneNumber.Text = myCollection.ToString();
                                    if ("department".Equals(ldapField))
                                        this.textDepartment.Text = myCollection.ToString();                                    
                                     if ("title".Equals(ldapField))
                                        this.textTitle.Text = myCollection.ToString();
                                    if ("whencreated".Equals(ldapField))
                                        this.textCreated.Text = myCollection.ToString();
                                    if ("mail".Equals(ldapField))
                                        this.textEmail.Text = myCollection.ToString();
                                    if ("description".Equals(ldapField))
                                        this.textDescription.Text = myCollection.ToString();
                                    if ("memberof".Equals(ldapField))
                                        this.richTextAreaInfoGrpAd.AppendText(myCollection + Environment.NewLine);

                                }
                            }
                        }
                        else
                        {
                            this.txtErrorMsg.BackColor = System.Drawing.Color.Red;
                            this.txtErrorMsg.Text = "No User Found!";
                        }



                        //string memberof = "memberof";
                        //foreach (Object myCollection in myResultPropColl[memberof])
                        //{
                        // this.richTextAreaInfoGrpAd.AppendText(myCollection + Environment.NewLine);
                        //}
                    }
                }
                this.tabControlPanel.Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Attenzione! Errore nell'interrogazione di AD." + ex.Message, "ERROR", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                this.txtErrorMsg.BackColor = System.Drawing.Color.Red;
                this.txtErrorMsg.Text = "No User Found!";
            }
        }                     

        private void clearAllTextArea()
        {
            if (!"".Equals(this.richTextAreaInfoGrpAd.Text.Trim())) this.richTextAreaInfoGrpAd.Clear();
            if (!"".Equals(this.txtErrorMsg.Text.Trim())) this.txtErrorMsg.Clear();
            if (!"".Equals(this.textDepartment.Text.Trim())) this.textDepartment.Clear();
            if (!"".Equals(this.textPhoneNumber.Text.Trim())) this.textPhoneNumber.Clear();
            if (!"".Equals(this.textCompany.Text.Trim())) this.textCompany.Clear();
            if (!"".Equals(this.textCreated.Text.Trim())) this.textCreated.Clear();
            if (!"".Equals(this.textTitle.Text.Trim())) this.textTitle.Clear();
            if (!"".Equals(this.textLoginId.Text.Trim())) this.textLoginId.Clear();
            if (!"".Equals(this.textEmail.Text.Trim())) this.textEmail.Clear();
            if (!"".Equals(this.textDescription.Text.Trim())) this.textDescription.Clear();
            if (!"".Equals(this.textLogonCount.Text.Trim())) this.textLogonCount.Clear();
            if (!"".Equals(this.textName.Text.Trim())) this.textName.Clear();
            if (!"".Equals(this.texLogonCount.Text.Trim())) this.texLogonCount.Clear();
            if (!"".Equals(this.txtErrorMsg.Text.Trim())) this.txtErrorMsg.BackColor = System.Drawing.Color.White;

        }

        private void buttonBrowser_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            DialogResult dlgResult = dlg.ShowDialog();
            if (dlgResult == DialogResult.OK)
            {
                this.txtPath.Text = dlg.FileName;
            }
        }

        private void buttonLoadData_Click(object sender, EventArgs e)
        {               
            System.IO.StreamReader streamReader = null;
            if (this.dtFormCsvFile ==null) this.dtFormCsvFile = new DataTable();            
            bool activeUpdateButton = true;
            try
            {
                string rowValue;
                string[] cellValue;
                
                if (System.IO.File.Exists(txtPath.Text))
                {
                    this.tabControlPanel.Cursor = Cursors.WaitCursor;
                    streamReader = new System.IO.StreamReader(this.txtPath.Text);

                        // Reading header
                   
                    rowValue = streamReader.ReadLine();
                    cellValue = rowValue.Split(';');
                    for (int i = 0; i <= cellValue.Count() - 1; i++)
                    {
                        //DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
                        // column.Name = cellValue[i];
                        //column.HeaderText = cellValue[i];
                        //this.dataGridView2.Columns.Add(column);
                        this.dtFormCsvFile.Columns.Add(cellValue[i]);
                    }
                
                    // Reading content
                    while (streamReader.Peek() != -1)
                    {
                        rowValue = streamReader.ReadLine();
                        cellValue = rowValue.Split(';');
                        //estraggo il primo valore che è l'uid e faccio il search
                        string uid = cellValue[0].Trim();
                        try
                        {
                            //NEW-VERSION: RECUPERO IL REALM UTILIZZANDO AD
                            String ADEntry = System.Environment.GetEnvironmentVariable("USERDNSDOMAIN");
                            //Console.WriteLine("AD Entry found: " + ADEntry);
                            using (DirectoryEntry de = new DirectoryEntry("LDAP://" + ADEntry))
                            {
                                using (DirectorySearcher adSearch = new DirectorySearcher(de))
                                {
                                    adSearch.Filter = string.Format("(sAMAccountName={0})", uid);
                                    adSearch.PropertiesToLoad.Add("displayname");
                                    adSearch.PropertiesToLoad.Add("title");

                                    SearchResult adSearchResult = adSearch.FindOne();
                                    if (adSearchResult != null)
                                    {
                                        // Get the properties of the 'mySearchResult'.
                                        ResultPropertyCollection myResultPropColl;
                                        myResultPropColl = adSearchResult.Properties;
                                        foreach (String ldapField in myResultPropColl.PropertyNames)
                                        {
                                            foreach (Object myCollection in myResultPropColl[ldapField])
                                            {
                                                if ("displayname".Equals(ldapField))
                                                    cellValue[1] = myCollection.ToString();
                                                if ("title".Equals(ldapField))
                                                {
                                                    //dovrebbe restituire un formtao del tipo
                                                    // 02948/BPM/BPMGROUP
                                                    string[] title = myCollection.ToString().Split('/');
                                                    cellValue[2] = title[0];
                                                    cellValue[3] = title[1];
                                                }
                                                cellValue[4] = "SI";
                                            }
                                        }
                                    }
                                    else
                                    {
                                        cellValue[4] = "NO";
                                    }
                                }
                            }
                            //fine ricerca
                            //this.dataGridView2.Rows.Add(cellValue);
                            this.dtFormCsvFile.Rows.Add(cellValue);
                        }
                        catch (Exception ex)
                        {
                            System.Windows.Forms.MessageBox.Show("Attenzione! Errore nell'interrogazione di AD." + ex.Message, "ERROR", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                            activeUpdateButton = false;
                        }                            
                        }
                        this.dataGridView2.DataSource = this.dtFormCsvFile;
                        this.tabControlPanel.Cursor = Cursors.Default;
                    }
                    else
                    {
                        MessageBox.Show("No File is Selected", "WARNING", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                        activeUpdateButton = false;
                    }
                }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Attenzione! Errore nel caricamento del file: " + ex.Message, "ERROR", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                activeUpdateButton = false;
            }
            finally
            {
                if (streamReader != null)
                    streamReader.Close();
            }
            this.buttonUpateData.Enabled = activeUpdateButton;            
        }

        private void buttonClearCompareTab_Click(object sender, EventArgs e)
        {
            this.textSheetChosen.Text = "Sheet1";
            this.txtPath.Clear();           
        }

        private System.Collections.Generic.List<string> headers = new System.Collections.Generic.List<string>(); 

        private void buttonUpateData_Click(object sender, EventArgs e)
        {
            this.tabControlPanel.Cursor = Cursors.WaitCursor;
            //eseguire l'update del file in browser a seguito dell'elaborazione                                  
            string delimiter = ";";               
            StringBuilder sb = new StringBuilder();      
            //manca la creazione della prima riga perchè fa le colonne (header) TODO
            
            foreach (DataColumn c in this.dtFormCsvFile.Columns)
            {
                headers.Add(c.ColumnName);
            }
            sb.Append(string.Join(delimiter, headers.ToArray())).Append(System.Environment.NewLine);
            foreach (DataRow r in this.dtFormCsvFile.Rows)
            {
                System.Collections.Generic.List<string> fields = new System.Collections.Generic.List<string>(); 
                foreach (object value in r.ItemArray) fields.Add(value.ToString()); 
                sb.Append(string.Join(delimiter,fields.ToArray())).Append(System.Environment.NewLine);
            }
            //format versione exapmle _v0.2.csv
            string newPath = this.txtPath.Text;
            string version = newPath.Replace(".csv",""); //tolto il csv
            int point = version.LastIndexOf('v');
            string oldVersion = version.Substring(point+1);
            int versione = Convert.ToInt32(oldVersion);
            int nuovaVersione = versione+1;            
            System.IO.File.WriteAllText(newPath.Replace("v"+oldVersion, "v"+nuovaVersione.ToString()), sb.ToString());
            this.buttonUpateData.Enabled = false;
            this.tabControlPanel.Cursor = Cursors.Default;
            MessageBox.Show("File creato", "INFO", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);                       
        }

        private void buttonLoadUserForMemeberOf_Click(object sender, EventArgs e)
        {
            this.tabControlPanel.Cursor = Cursors.WaitCursor;
            //this.clearCheckTab();
            string grpid = this.textGrpId.Text.Trim();
            if ("".Equals(grpid))
            {
                System.Windows.Forms.MessageBox.Show("Inserire un valore di gruppo per la ricerca.", "WARNING", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
            }
            else 
            {
                this.getAllUsersInGruop(grpid); 
            }
            this.tabControlPanel.Cursor = Cursors.Default;
        }

        private void getAllUsersInGruop(string grpid) {
            try
            {
                //NEW-VERSION: RECUPERO IL REALM UTILIZZANDO AD
                String ADEntry = System.Environment.GetEnvironmentVariable("USERDNSDOMAIN");
                //Console.WriteLine("AD Entry found: " + ADEntry);
                using (DirectoryEntry de = new DirectoryEntry("LDAP://" + ADEntry))
                {                    
                    using (DirectorySearcher adSearch = new DirectorySearcher(de))
                    {
                        adSearch.Filter = String.Format("(cn=*{0}*)", grpid);
                        adSearch.PropertiesToLoad.Add("SAMAccountName");
                        adSearch.PropertiesToLoad.Add("member");
                        StringBuilder allUsers = new StringBuilder();
                        SearchResult result;
                        SearchResultCollection resultCol = adSearch.FindAll();
                        if ((resultCol == null)||(resultCol.Count ==0))
                        {
                            this.textToolbarCheck.BackColor = System.Drawing.Color.Red;
                            this.textToolbarCheck.Text = "No User Found!";
                        }
                        else
                        {
                            for (int counter = 0; counter < resultCol.Count; counter++)
                            {
                                result = resultCol[counter];                               
                                for (int c = 0; c < result.Properties["member"].Count; c++)
                                {
                                    allUsers.Append((String)result.Properties["member"][c]).Append(System.Environment.NewLine);
                                }                                       
                            }                            
                            this.richTextBoxUserGrp.AppendText(allUsers.ToString());
                        }                      
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Attenzione! Errore nell'interrogazione di AD." + ex.Message, "ERROR", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                this.textToolbarCheck.BackColor = System.Drawing.Color.Red;
                this.textToolbarCheck.Text = "No User Found!";
            }
        }

        private void textGrpId_TextChanged(object sender, EventArgs e)
        {
            if (!"".Equals(this.richTextBoxUserGrp.Text.Trim())) this.richTextBoxUserGrp.Clear();
            if (!"".Equals(this.textToolbarCheck.Text.Trim())) 
            {
                this.textToolbarCheck.Clear();
                this.textToolbarCheck.BackColor = System.Drawing.Color.White;
            }

        }

        private void textUserId_TextChanged(object sender, EventArgs e)
        {
            //sarebbe interessante interecettare gli eventi; input da tastiera o ctrl-v richiedono il clear, gli altri no
            if (!"".Equals(this.textBoxSurname.Text.Trim())) this.textBoxSurname.Clear();
            this.clearAllTextArea();
            this.txtErrorMsg.BackColor = System.Drawing.Color.White;
        }

        private void textBoxSurname_TextChanged(object sender, EventArgs e)
        {
            //sarebbe interessante interecettare gli eventi; input da tastiera o ctrl-v richiedono il clear, gli altri no
            if (!"".Equals(this.textUserId.Text.Trim())) this.textUserId.Clear();            
            this.clearAllTextArea();
            this.txtErrorMsg.BackColor = System.Drawing.Color.White;
        }
    }
}   
